package ru.electron.menu.provider;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.provider.BaseColumns;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static ru.electron.menu.provider.MenuProvider.*;

public class MenuInitializator {

     private static ContentValues jTagToContentValues(JSONObject jTag) throws JSONException {
         ContentValues res = new ContentValues();
         res.put(BaseColumns._ID,  jTag.getInt("id"));
         res.put(KEY_TAG_NAME, jTag.getString("name"));
         return res;
     }


     private static ContentValues jDishToContentValues(JSONObject jDish) throws JSONException {
         ContentValues res = new ContentValues();
         res.put(BaseColumns._ID, jDish.getInt("id"));
         res.put(KEY_URI, jDish.getString("picture"));
         res.put(KEY_PRICE, (float)jDish.getDouble("price"));
         res.put(KEY_DESCRIPTION, jDish.getString("description"));
         res.put(KEY_DISH_NAME, jDish.getString("name"));
         res.put(KEY_TAG_ID, jDish.getString("tag-id"));
         res.put(KEY_AVAILABILITY, jDish.getInt("available"));
         return  res;
     }


     public void init(Context context, String jsonMenu){

         ContentResolver resolver = context.getContentResolver();
         try {
             JSONObject jMenu = new JSONObject(jsonMenu);
             JSONArray jTags = jMenu.getJSONArray("tags");
             JSONArray jDishes =  jMenu.getJSONArray("dishes");

             for (int i = 0; i < jTags.length(); i++){
                 JSONObject tag = jTags.getJSONObject(i);
                 ContentValues values =  jTagToContentValues(tag);
                 resolver.insert(URI_TAGS, values);
             }

             for(int i = 0; i < jDishes.length(); i++){
                 JSONObject dish = jDishes.getJSONObject(i);
                 ContentValues values = jDishToContentValues(dish);
                 resolver.insert(URI_DISHES, values);
             }


         } catch (JSONException e) {
             e.printStackTrace();
         }
     }


}
